package com.derekandbritt.booST.data;

import java.util.HashMap;

public class Cache<T> {

	private HashMap<String, CacheObject> cache = new HashMap<String, CacheObject>();
	private long cacheLife = 600000; // DEFAULT IS 10 MINUTES
	
	private class CacheObject {
		
		public T item;
		public long cachedTime;
		
		CacheObject(T item, long cachedTime) {
			this.item = item;
			this.cachedTime = cachedTime;
		}
		
		boolean isValid() {
			return ((cachedTime + cacheLife) > System.currentTimeMillis());
		}
	}
	
	public Cache() { }
	
	public Cache(long cacheLife) {
		this.cacheLife = cacheLife;
	}
	
	public void clearCache() {
		cache.clear();
	}
	
	public void updateCache(String id, T item) {
		this.cache.put(id, new CacheObject(item, System.currentTimeMillis()));
	}	
	
	public boolean containsItem(String id) {
		return getItem(id) != null;
	}
	
	public T getItem(String id) {
		CacheObject object = cache.get(id);
		if(object != null && object.isValid()) {
			return object.item;
		} else {
			return null;
		}
	}
}
